<template>
  <div>
    <div
      class="-mt-46 h-[calc(100vh-15px)] custom-navbar-wrapper pt-46 flex flex-col"
    >
      <div class="pt-20 px-15">
        <!-- 视频类型选项卡 -->
        <NormalTabs
          :tabs="TYPES"
          :active-id="activeTypeId"
          :tab-class="tabsClass"
          @update:active-id="handleTypeChange"
        />
      </div>
      <div
        ref="scrollContainer"
        class="scroll-view scroll-view--vertical hide-scrollbar flex-1"
      >
        <div ref="scrollContent" class="scroll-view__content">
          <!-- 视频列表 -->
          <div class="px-15">
            <div
              v-for="item in historyData.records"
              :key="item.id"
              class="h-80 flex items-center border-b-1 border-F5F5F5"
            >
              <div class="flex flex-col">
                <div class="text-14">{{ item.assetShowDesc }}</div>
                <div class="mt-4 text-12 text-999999">
                  {{ item.createTime }}
                </div>
              </div>
              <div class="text-16 ml-auto font-bold">
                {{ item.detailType == 1 ? "+" : "-" }}{{ item.amount }}
              </div>
            </div>
          </div>

          <!-- 加载状态 -->
          <div v-if="isLoading" class="py-20 flex justify-center items-center">
            <van-loading size="24px" vertical>
              <span class="text-13 text-999 mt-10">加载中...</span>
            </van-loading>
          </div>

          <!-- 没有更多数据 -->
          <div
            v-if="isFinished && historyData.records.length > 0"
            class="py-15 text-center text-13 text-999"
          >
            <span class="inline-block px-10 py-5 rounded-full bg-gray-100"
              >没有更多数据了</span
            >
          </div>

          <!-- 空状态 -->
          <div
            v-if="!isLoading && historyData.records.length === 0"
            class="py-50 text-center"
          >
            <img
              :src="`${IMG_CDN_39}/common/empty-history.png`"
              class="w-150 mx-auto"
              alt="空状态"
            />
            <div class="mt-20 text-15 text-999">暂无历史记录</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref, nextTick, onBeforeUnmount } from "vue";
import NormalTabs from "@/components/NormalTabs/index.vue";
import type { PageResponse } from "src/types";
import { IMG_CDN_39 } from "@/constants";
import { showToast } from "vant";
import {
  getUserAiCoinAssetDetail,
  UserAiCoinAssetDetailInfoData
} from "@/api/AICoinRecord";

defineOptions({
  name: "AICoinRecord"
});

// 样式配置
const tabsClass = ref({
  textColor: "text-999999"
});
// 视频类型配置
const TYPES = [
  { id: "0", name: "全部" },
  { id: "1", name: "消耗" },
  { id: "2", name: "充值" }
];
const activeTypeId = ref<string>("0");

// 历史记录数据
const historyData = ref<PageResponse<UserAiCoinAssetDetailInfoData>>({
  current: 1,
  pages: 0,
  records: [],
  size: 24,
  total: 0
});

// 加载状态
const isLoading = ref(false);
const isFinished = ref(false);

// 滚动容器引用
const scrollContainer = ref<HTMLElement | null>(null);
const scrollContent = ref<HTMLElement | null>(null);

// 处理类型切换
const handleTypeChange = (typeId: string) => {
  activeTypeId.value = typeId;
  // 重置分页数据
  historyData.value = {
    current: 1,
    pages: 0,
    records: [],
    size: 24,
    total: 0
  };
  loadHistoryData();
};

// 加载函数
const loadHistoryData = async (loadMore = false) => {
  if (isLoading.value) return;

  try {
    isLoading.value = true;
    const currentData = historyData.value;

    const nextPage = loadMore ? currentData.current + 1 : 1;
    const params = {
      pageNo: nextPage,
      pageSize: 24,
      type: activeTypeId.value
    };

    const res = await getUserAiCoinAssetDetail(params);

    historyData.value = loadMore
      ? {
          ...res,
          records: [...currentData.records, ...res.records]
        }
      : res;

    isFinished.value = res.current >= res.pages;

    if (loadMore && res.records.length > 0) {
      showToast({
        message: `加载了 ${res.records.length} 条新记录`,
        position: "bottom"
      });
    }
  } catch (error) {
    console.error("加载失败:", error);
    showToast("加载失败，请稍后再试");
  } finally {
    isLoading.value = false;
    nextTick(() => {
      if (scrollContainer.value && scrollContent.value) {
        scrollContainer.value.addEventListener("scroll", handleScroll);
      }
    });
  }
};

// 处理滚动事件
const handleScroll = () => {
  if (
    !scrollContainer.value ||
    !scrollContent.value ||
    isLoading.value ||
    isFinished.value
  )
    return;

  const containerHeight = scrollContainer.value.clientHeight;
  const contentHeight = scrollContent.value.scrollHeight;
  const scrollTop = scrollContainer.value.scrollTop;
  const distanceToBottom = contentHeight - (scrollTop + containerHeight);

  if (distanceToBottom < 50) {
    scrollContainer.value.removeEventListener("scroll", handleScroll);
    loadHistoryData(true);
  }
};

onMounted(() => {
  // 初始加载数据
  loadHistoryData();
});

onBeforeUnmount(() => {
  if (scrollContainer.value) {
    scrollContainer.value.removeEventListener("scroll", handleScroll);
  }
});
</script>

<style scoped lang="less">
.custom-navbar-wrapper {
  min-height: 100%;
  background-image: linear-gradient(
    180deg,
    #d5e2ff 0%,
    #ffffff 16%,
    #ffffff 100%
  );
  background-repeat: no-repeat;
}

.loading-circle {
  border: 3px solid rgba(255, 255, 255, 0.3);
  border-top: 3px solid #ffffff;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.scroll-view__content {
  padding-bottom: 20px;
}
</style>
